/**
 * 将.doc文件转换成html文件。支持图片、表格。
 * 不支持.docx文件转换。
 */
package com.zooltech.demos.poi;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;

/**
 * Word转html格式.
 *
 * @author yinxb
 *
 */
public class Word2Html {
	/**
	 * 输入文档。
	 */
	private static final String INPUT_FILE = "./测试文档.doc";
	/**
	 * 输出文档。
	 */
	private static final String OUTPUT_FILE = "./测试文档.html";

	/**
	 * 主方法.
	 * 
	 * @param args
	 *            命令行参数
	 * @throws Exception
	 *             异常
	 */
	public static void main(String[] args) throws Exception {
		convert2Html(INPUT_FILE, OUTPUT_FILE);
	}

	/**
	 * 内容写入文件.
	 * 
	 * @param content
	 *            内容串
	 * @param path
	 *            文件路径及名称串
	 */
	public static void writeFile(String content, String path) {
		FileOutputStream fos = null;
		BufferedWriter bw = null;
		try {
			File file = new File(path);
			fos = new FileOutputStream(file);
			bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
			bw.write(content);
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {
				if (bw != null)
					bw.close();
				if (fos != null)
					fos.close();
			} catch (IOException ie) {
			}
		}
	}

	/**
	 * 转换方法.
	 * 
	 * @param fileName
	 *            输入文件
	 * @param outPutFile
	 *            输出文件
	 * @throws TransformerException
	 *             转换异常
	 * @throws IOException
	 *             输入输出异常
	 * @throws ParserConfigurationException
	 *             解析异常
	 */
	public static void convert2Html(String fileName, String outPutFile)
			throws TransformerException, IOException,
			ParserConfigurationException {

		final String fs = File.separator;
		int fpos = outPutFile.indexOf(fs);
		String fp, fn;
		if (fpos < 0) {
			//throw new IOException("OutPutFile path error!");
			fp=".";
			fn=outPutFile;
		}else{
			fp = outPutFile.substring(0, fpos);
			fn = outPutFile.substring(fpos);
		}
		final String fpp = fp + fs + "pics";
		File f = new File(fpp);
		if (!f.isDirectory())
			f.mkdir();

		HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(
				fileName));// WordToHtmlUtils.loadDoc(new
							// FileInputStream(inputFile));
		
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder()
						.newDocument());
		wordToHtmlConverter.setPicturesManager(new PicturesManager() {
			public String savePicture(byte[] content, PictureType pictureType,
					String suggestedName, float widthInches, float heightInches) {
				return fpp + fs + suggestedName;
			}
		});
		wordToHtmlConverter.processDocument(wordDocument);
		// save pictures
		List pics = wordDocument.getPicturesTable().getAllPictures();
		if (pics != null) {
			for (int i = 0; i < pics.size(); i++) {
				Picture pic = (Picture) pics.get(i);
				// System.out.println();
				try {
					pic.writeImageContent(new FileOutputStream(fpp + fs
							+ pic.suggestFullFileName()));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
		Document htmlDocument = wordToHtmlConverter.getDocument();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		DOMSource domSource = new DOMSource(htmlDocument);
		StreamResult streamResult = new StreamResult(out);

		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		out.close();
		writeFile(new String(out.toByteArray()), outPutFile);
	}
}
